package com.bigchun.woodhunter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;

import myapp.MyApp;
import util.MyLog;
import util.PreferenceUtil;
import util.RequestManager;

public class SplashActivity extends BaseActivity {


    private MyApp myApp;
    private Context context;
    private SharedPreferences spuserInfo;
    private String token;
    private String apptype = "0";
    private JSONObject textData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 打包注意事项
         * 1，启动页的默认的apptype要修改，木头为0，熙然为1
         * 2，熙然默认英文
         * 3，app名字需要更改
         * 4，glideutils需要更改默认图片
         *
         */


//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏
//        Objects.requireNonNull(getSupportActionBar()).hide();//隐藏标题栏
        setContentView(R.layout.activity_splash);
        myApp = (MyApp) getApplicationContext();
        context = this;
        spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
        token = spuserInfo.getString("token", "");
        apptype = spuserInfo.getString("apptype", "");
        PreferenceUtil.commitString("language", "zh");//en   zh
        //如果本地没有存储默认的方式，默认木头为0，熙然为1     GlideUtils类中，占位图也要更换
        String defaultApptype = "1";
        if ("".equals(apptype)) {
            spuserInfo.edit().putString("apptype", defaultApptype).commit();
        }
        apptype = spuserInfo.getString("apptype", defaultApptype);

        String isagree = spuserInfo.getString("isagree", "");
        if (!"1".equals(isagree)) {
            showNoticeDialog();
        }else{
            getContentData();
        }

    }


    /**
     * 获取配置信息
     */
    private void getconfigData() {

        String url = myApp.getWebConfig() + "/api/index/my_config";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 4;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    String domain = data.getString("domain");
                    String urlstr = data.getString("url");
                    String z_about = data.getString("z_about");
                    String j_about = data.getString("j_about");
                    String e_about = data.getString("e_about");
                    String z_formula = data.getString("z_formula");
                    spuserInfo.edit().putString("domain", domain).commit();
                    spuserInfo.edit().putString("urlstr", urlstr).commit();
                    spuserInfo.edit().putString("z_about", z_about).commit();
                    spuserInfo.edit().putString("e_about", e_about).commit();
                    spuserInfo.edit().putString("j_about", j_about).commit();
                    spuserInfo.edit().putString("z_formula", z_formula).commit();
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    /**
     * 获取配置信息
     */
    private void getContentData() {
        String string = PreferenceUtil.getString("language", "");
        if ("".equals(string)) {
            Locale locale = Locale.getDefault();
            string = locale.getLanguage();
            switchLanguage(string);
        }
        MyLog.e("手机系统语言", "语言     " + string);
        String url = myApp.getWebConfig() + "/api/index/apptran";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("lang", string);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    textData = jsonObject.getJSONObject("data");
//                    textData = new Gson().fromJson(data.toString(), new TypeToken<ContentDataBean.DataBean>() {
//                    }.getType());
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Intent intent = null;
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    getconfigData();
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();

                    break;
                case 1:


                    getconfigData();
                    try {
                        Toast.makeText(context, textData.getString("net_error"), Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 2:
                    Thread myThread2 = new Thread() {//创建子线程
                        @Override
                        public void run() {
                            try {
                                sleep(2000);//使程序休眠五秒
                                if (!"".equals(token)) {
                                    Intent it = new Intent(getApplicationContext(), MainActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                } else {
                                    Intent it = new Intent(getApplicationContext(), LoginActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    myThread2.start();//启动线程
                    break;
                case 3:
                    getconfigData();
                    spuserInfo.edit().putString("textData", textData.toString()).commit();
                    break;
                case 4:
                    String strstr = (String) msg.obj;
                    Toast.makeText(context, strstr, Toast.LENGTH_LONG).show();
                    Thread myThread = new Thread() {//创建子线程
                        @Override
                        public void run() {
                            try {
                                sleep(2000);//使程序休眠五秒
                                if (!"".equals(token)) {
                                    Intent it = new Intent(getApplicationContext(), MainActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                } else {
                                    Intent it = new Intent(getApplicationContext(), LoginActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    myThread.start();//启动线程
                    break;
                case 5:

                    Thread myThread1 = new Thread() {//创建子线程
                        @Override
                        public void run() {
                            try {
                                sleep(2000);//使程序休眠五秒
                                if (!"".equals(token)) {
                                    Intent it = new Intent(getApplicationContext(), MainActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                } else {
                                    Intent it = new Intent(getApplicationContext(), LoginActivity.class);//启动MainActivity
                                    startActivity(it);
                                    finish();//关闭当前活动
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    myThread1.start();//启动线程
                    break;
                case 12:
                    Log.e("无网络", "无网络");
                    if (!"".equals(token)) {
                        Intent it = new Intent(getApplicationContext(), MainActivity.class);//启动MainActivity
                        startActivity(it);
                        finish();//关闭当前活动
                    } else {
                        Intent it = new Intent(getApplicationContext(), LoginActivity.class);//启动MainActivity
                        startActivity(it);
                        finish();//关闭当前活动
                    }
                    break;
            }
        }
    };
    private AlertDialog dialog;

    private void showNoticeDialog() {
        dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        //对话框弹出后点击或按返回键不消失;
        dialog.setCancelable(false);

        final Window window = dialog.getWindow();

        if (window != null) {

            window.setContentView(R.layout.item_dialog_agree);
            window.setGravity(Gravity.CENTER);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            //设置属性
            final WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
//            params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
//            params.dimAmount = 0.5f;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
            TextView textView = window.findViewById(R.id.tv_1);
            TextView tvCancel = window.findViewById(R.id.tv_cancel);
            TextView tvAgree = window.findViewById(R.id.tv_agree);
            tvAgree.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                    spuserInfo.edit().putString("isagree", "1").commit();


                    getContentData();


                }
            });
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                    spuserInfo.edit().putString("isagree", "0").commit();
                    finish();
                }
            });
            String str = "请你务必审慎阅读、充分理解\"服务协议”和“隐私政策”各条款，包括但不限于:为了向你提供内容展示，图片保存等服务，我们需要收集你的设备信息、操作日志等个人信息。你可以在“设置\"中查看、变更、删除个人信息并管理你的授权。\n" +
                    "你可阅读《服务协议》和《隐私政策》了解详细信息。如你同意，请点击“同意”开始接受我们的服务。";

            SpannableStringBuilder ssb = new SpannableStringBuilder();
            ssb.append(str);
            final int start = str.indexOf("《");//第一个出现的位置
            ssb.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    Intent intent = new Intent(context, WebviewForXieyiActivity.class);
                    if ("0".equals(apptype)) {
                        intent.putExtra("url", MyApp.siteurl+"/template/mood.html");
                    } else if ("1".equals(apptype)) {
                        intent.putExtra("url", MyApp.siteurl+"/template/seeland.html");
                    }
                    startActivity(intent);
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(getResources().getColor(R.color.colorAccent));       //设置文件颜色
                    // 去掉下划线
                    ds.setUnderlineText(false);
                }

            }, start, start + 6, 0);

            final int end = str.lastIndexOf("《");//最后一个出现的位置

            ssb.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {


                    Intent intent = new Intent(context, WebviewForXieyiActivity.class);
                    if ("0".equals(apptype)) {
                        intent.putExtra("url", MyApp.siteurl+"/api/formula/privacy");
                    } else if ("1".equals(apptype)) {
                        intent.putExtra("url", MyApp.siteurl+"/api/formula/see_privacy");
                    }

                    startActivity(intent);
                }

                @Override

                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(getResources().getColor(R.color.colorAccent));       //设置文件颜色
                    // 去掉下划线

                    ds.setUnderlineText(false);
                }

            }, end, end + 6, 0);

            textView.setMovementMethod(LinkMovementMethod.getInstance());
            textView.setText(ssb, TextView.BufferType.SPANNABLE);
        }


    }

}
